package project.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import project.service.FileService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RequestMapping(value = "/file")
@CrossOrigin
@RestController
public class FileController {

    @Autowired
    FileService fileService;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping(value = "/upload")
    public Map<String,Object> upload(@RequestParam("file") MultipartFile file,@RequestParam("loginName") String loginName) throws  Exception {

        String newFileName = UUID.randomUUID().toString().substring(0, 10) + "-" + file.getOriginalFilename();
        String url = fileService.uploadFile(file, newFileName);
        redisTemplate.opsForValue().set(loginName + "_avatar", newFileName);
        Map<String,Object> file1 = new HashMap<>();
        file1.put("data", url);
        return file1;
    }
    /**
     * 下载接口
     */
    @GetMapping (value = "/download")
    public void download(@RequestParam String loginName, HttpServletRequest request, HttpServletResponse response) {
        String fileName = (String) redisTemplate.opsForValue().get(loginName + "_avatar");
        System.out.println("username="+loginName);
        System.out.println("fileName="+fileName);
        fileService.downloadFile(fileName, request, response);
    }

    /**
     * 删除接口
     */
    @DeleteMapping("/delete")
    public Map<String,Object> deleteFile(@RequestParam String loginName) {
        String fileName = (String) redisTemplate.opsForValue().get(loginName + "_avatar");
        redisTemplate.opsForValue().set(loginName + "_avatar", "default.jpg");
        boolean flag = fileService.deleteFile(fileName);
        Map<String,Object> file2 = new HashMap<>();
        file2.put("data", flag);
        return file2;
    }

}
